package com.example.hc05_connect;

import android.Manifest;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothGatt;
import android.bluetooth.BluetoothGattCallback;
import android.bluetooth.BluetoothGattCharacteristic;
import android.bluetooth.BluetoothGattDescriptor;
import android.bluetooth.BluetoothGattService;
import android.bluetooth.BluetoothManager;
import android.bluetooth.BluetoothProfile;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import androidx.activity.EdgeToEdge;
import androidx.activity.result.ActivityResultLauncher;
import androidx.activity.result.contract.ActivityResultContracts;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
import androidx.core.graphics.Insets;
import androidx.core.view.ViewCompat;
import androidx.core.view.WindowInsetsCompat;

import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;
import java.util.UUID;

public class MainActivity extends AppCompatActivity implements View.OnClickListener{

    private static final String TAG = "mainActivity";
    private ArrayList<BluetoothDevice> readyDevices = new ArrayList<>();
    private List<String> deviceNames = new ArrayList<>();
    private ArrayAdapter<String> btAdapter;
    private BluetoothDevice bluetoothDevice = null;
    TextView tv_showConnect = null;
    TextView tv_showRecvStr = null;
    private static final UUID BLE_UART_SERVICE_UUID =
            UUID.fromString("0000ffe0-0000-1000-8000-00805f9b34fb");

    // RX 特征 (接收数据)
    private static final UUID BLE_RX_CHARACTERISTIC_UUID =
            UUID.fromString("0000ffe1-0000-1000-8000-00805f9b34fb");

    // TX 特征 (发送数据)
    private static final UUID BLE_TX_CHARACTERISTIC_UUID =
            UUID.fromString("0000ffe2-0000-1000-8000-00805f9b34fb");

    private final ActivityResultLauncher<Intent> enableBluetoothLauncher = registerForActivityResult(
            new ActivityResultContracts.StartActivityForResult(),
            result -> {
                if (result.getResultCode() == Activity.RESULT_OK) {
                    // 蓝牙已启用，继续执行蓝牙操作
                    Log.d(TAG, "Bluetooth enabled");
                    Toast.makeText( this,"蓝牙打开中",Toast.LENGTH_SHORT ).show();
                } else {
                    // 用户未启用蓝牙，可以提示用户
                    Toast.makeText( this,"蓝牙没有打开",Toast.LENGTH_SHORT ).show();
                    Log.d(TAG, "Bluetooth denied");
                }
            }
    );
    private BluetoothAdapter mBluetoothAdapter = null;
    private BluetoothGatt mBluetoothGatt;
    private boolean isLastSuccess = true;
    private boolean isConnected = false;
    private EditText editText_ssid = null;
    private EditText editText_pwd = null;
    private EditText editText_ip = null;
    private EditText editText_port = null;
   private  Button btn_trans = null;

    @SuppressLint("MissingInflatedId")
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        EdgeToEdge.enable(this);
        setContentView(R.layout.activity_main);
        ViewCompat.setOnApplyWindowInsetsListener(findViewById(R.id.main), (v, insets) -> {
            Insets systemBars = insets.getInsets(WindowInsetsCompat.Type.systemBars());
            v.setPadding(systemBars.left, systemBars.top, systemBars.right, systemBars.bottom);
            return insets;
        });
        editText_ssid = findViewById( R.id.editText_ssid );
        editText_pwd = findViewById( R.id.editText_pwd );


        if (ContextCompat.checkSelfPermission(this, Manifest.permission.BLUETOOTH_CONNECT) != PackageManager.PERMISSION_GRANTED) {
            ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.BLUETOOTH_CONNECT}, 1);
        }
        if (ContextCompat.checkSelfPermission(this, Manifest.permission.BLUETOOTH_SCAN) != PackageManager.PERMISSION_GRANTED) {
            ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.BLUETOOTH_SCAN}, 1);
        }
        if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
            ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, 1);
        }

        BluetoothManager bm = (BluetoothManager) getSystemService(Context.BLUETOOTH_SERVICE);
        mBluetoothAdapter = bm.getAdapter(); // 获取蓝牙适配器
        BluetoothAdapter bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
        if (bluetoothAdapter == null || !bluetoothAdapter.isEnabled()) {
            Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
            enableBluetoothLauncher.launch(enableBtIntent);
        }

        ListView lv_bluetooth = findViewById(R.id.listView_bluetooth);
        Set<BluetoothDevice> pairDecices = mBluetoothAdapter.getBondedDevices();
        if( pairDecices != null && pairDecices.size()>0  ){
            readyDevices.clear();
            deviceNames.clear();
            for( BluetoothDevice device : pairDecices  ){
                readyDevices.add( device );
                deviceNames.add ( device.getName() );
            }
            btAdapter  = new ArrayAdapter<>(this, android.R.layout.simple_list_item_1 ,deviceNames);
            lv_bluetooth.setAdapter( btAdapter);
            Toast.makeText( this,"蓝牙有打开",Toast.LENGTH_SHORT ).show();
        }
        else{
            Toast.makeText( this,"蓝牙没有打开",Toast.LENGTH_SHORT ).show();
        }
        tv_showRecvStr = findViewById(R.id.textView_recvStr );
        tv_showConnect = findViewById( R.id.textView_connectState );
        editText_ip = findViewById( R.id.editText_ip );
        editText_port = findViewById( R.id.editText_port );

        lv_bluetooth.setOnItemClickListener(
                new AdapterView.OnItemClickListener() {
                    @SuppressLint("MissingPermission")
                    @Override
                    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                        bluetoothDevice = readyDevices.get(position);
                        mBluetoothGatt = bluetoothDevice.connectGatt(MainActivity.this, false,bluetoothGattCallback );
                    }
                }
        );


        Button btn_selectBle = findViewById( R.id.button_selectBle );
        btn_selectBle.setOnClickListener(this);
        btn_trans = findViewById( R.id.button_trans );
        btn_trans.setOnClickListener(this);

    }


    @Override
    public void onClick(View v) {
        if (v.getId() == R.id.button_selectBle) {
            startActivity(new Intent(this, BleSelectActivity.class));
        }
        else if( v.getId() == R.id.button_trans){
            String ssid = "SSD:"+editText_ssid.getText().toString() ;// + "\r\n";
            String pwd = "PWD:"+editText_pwd.getText().toString();//+ "\r\n";
            String ip = "TCP:"+editText_ip.getText().toString();//+ "\r\n";
            String port = "POR:"+editText_port.getText().toString();//+ "\r\n";

            if (ssid.isEmpty() || pwd.isEmpty()|| ip.isEmpty() || port.isEmpty() ) {
                // 输入为空处理
                Toast.makeText( this,"没有完整输入",Toast.LENGTH_SHORT ).show();
            } else {
                // 有效输入处理
//                sendDataToHc05( "ssid:"+ ssid);
                List<String> msgList = new ArrayList<>();
                msgList.add(ssid );
                msgList.add(pwd );
                msgList.add(ip );
                msgList.add(port );
                new MessageThread(msgList).start(); // 启动消息发送线程
            }
        }
    }

    private final BluetoothGattCallback bluetoothGattCallback = new BluetoothGattCallback() {
        @SuppressLint("MissingPermission")
        @Override
        public void onConnectionStateChange(BluetoothGatt gatt, int status, int newState) {
            if (newState == BluetoothProfile.STATE_CONNECTED) {
                // successfully connected to the GATT Server
                gatt.discoverServices();
                Log.d(TAG, "successfully connected to the GATT Server " );
                isConnected = true;
                runOnUiThread(() -> {
                    String desc = String.format("已连接BLE服务端，对方名称为“%s”，MAC地址为%s",
                            bluetoothDevice.getName(), bluetoothDevice.getAddress());
                    Log.d(TAG, desc );
                    tv_showConnect.setText( desc );
                });

            } else if (newState == BluetoothProfile.STATE_DISCONNECTED) {
                // disconnected from the GATT Server
                mBluetoothGatt.close();
                isConnected = false;
                Log.d(TAG, "disconnected from the GATT Server" );
                runOnUiThread(() -> {
                    String desc = String.format("BLE服务端关闭 ");
                    Log.d(TAG, desc );
                    tv_showConnect.setText( desc );
                });
            }
        }

        public void onServicesDiscovered(final BluetoothGatt gatt, int status) {
            super.onServicesDiscovered(gatt, status);
            if (status == BluetoothGatt.GATT_SUCCESS) {
                BluetoothGattService uartService = gatt.getService(BLE_UART_SERVICE_UUID);
                Log.d(TAG, "onServicesDiscovered status is  " + status);
                if (uartService != null) {
                    // 2. 获取 RX 特征 (接收数据)
                    BluetoothGattCharacteristic rxChar = uartService.getCharacteristic(BLE_RX_CHARACTERISTIC_UUID);
                    if (rxChar != null) {
                        enableNotifications(gatt, rxChar);
                    } else {
                        Log.e(TAG, "RX 特征未找到");
                    }
                } else {
                    Log.e(TAG, "UART 服务未找到");
                }
            }
        }
        @Override
        public void onCharacteristicChanged(BluetoothGatt gatt, BluetoothGattCharacteristic chara) {
            super.onCharacteristicChanged(gatt, chara);
            String message = new String(chara.getValue()); // 把服务端返回的数据转成字符串
            Log.d(TAG, "onCharacteristicChanged "+message);
            tv_showRecvStr.setText( "Recv Str: "+ message+ "\n" );

        }
        public void onCharacteristicWrite(BluetoothGatt gatt, BluetoothGattCharacteristic chara, int status) {
            super.onCharacteristicWrite(gatt, chara, status);
            Log.d(TAG, "onCharacteristicWrite status="+status);
            if (status == BluetoothGatt.GATT_SUCCESS) {
                isLastSuccess = true;
            } else {
                Log.d(TAG, "write fail->" + status);
            }
        }
    };

    @SuppressLint("MissingPermission")
    private void enableNotifications(BluetoothGatt gatt, BluetoothGattCharacteristic characteristic) {
        // 1. 在本地启用通知
        gatt.setCharacteristicNotification(characteristic, true);
        // 2. 获取 CCCD 描述符
        BluetoothGattDescriptor descriptor = characteristic.getDescriptor(UUID.fromString("00002902-0000-1000-8000-00805f9b34fb"));
        if (descriptor != null) {
            // 3. 设置通知值
            descriptor.setValue(BluetoothGattDescriptor.ENABLE_NOTIFICATION_VALUE);
            // 4. 写入描述符
            gatt.writeDescriptor(descriptor);
        } else {
            Log.e(TAG, "未找到 CCCD 描述符");
        }
    }


    @SuppressLint("MissingPermission")
    public void sendDataToHc05(String message) {
        if (mBluetoothGatt == null) {
            Log.e(TAG, "未连接 GATT");
            return;
        }
        // 1. 获取 UART 服务
        BluetoothGattService uartService = mBluetoothGatt.getService(BLE_UART_SERVICE_UUID);
        if (uartService == null) {
            Log.e(TAG, "未找到 UART 服务");
            return;
        }
        // 2. 获取 TX 特征
        BluetoothGattCharacteristic txChar = uartService.getCharacteristic(BLE_TX_CHARACTERISTIC_UUID);
        if (txChar == null) {
            Log.e(TAG, "未找到 TX 特征");
            return;
        }
        // 3. 设置数据 (转换为字节数组)
        byte[] data = message.getBytes(StandardCharsets.UTF_8);
        txChar.setValue(data);
        // 4. 写入特征 (使用 WRITE_TYPE_NO_RESPONSE 提高速度)
        txChar.setWriteType(BluetoothGattCharacteristic.WRITE_TYPE_DEFAULT);
        mBluetoothGatt.writeCharacteristic(txChar);
    }



    private class MessageThread extends Thread {
        private List<String> msgList; // 消息列表
        public MessageThread( List<String> msgList) {
            this.msgList = msgList;
        }

        @Override
        public void run() {
            if( msgList.size() == 4 ){
                Log.d(TAG, "got all message" );
            }
            else {
                Log.d(TAG, "got all message" );
            }
            for (int i=0; i< msgList.size(); i++) {
                if (isLastSuccess) { // 需要等到上一条回调成功之后，才能发送下一条消息
                    isLastSuccess = false;
                    Log.d(TAG, "writeCharacteristic "+msgList.get(i));
                    try {
                        sleep(800);
                        sendDataToHc05( msgList.get(i)  );
                    } catch (InterruptedException e) {throw new RuntimeException(e);}

                }
                else {
                    i--;
                }// 休眠300毫秒，等待上一条的回调通知
                try {sleep(800);}
                catch (InterruptedException e) {e.printStackTrace();}
            }
        }
    }


}